/**
 * 采购入库 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Purchase.PWMainForm", {
  extend: "PSI.AFX.Form.MainForm",

  config: {
    permission: null
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      items: [{
        tbar: me.getToolbarCmp(),
        id: me.buildId(me, "panelQueryCmp"),
        region: "north",
        height: 95,
        layout: "fit",
        border: 0,
        header: false,
        collapsible: true,
        collapseMode: "mini",
        layout: {
          type: "table",
          columns: 6
        },
        bodyCls: "PSI-Query-Panel",
        items: me.getQueryCmp()
      }, {
        region: "center",
        layout: "border",
        ...PSI.Const.BODY_PADDING,
        border: 0,
        items: [{
          region: "center",
          layout: "fit",
          border: 0,
          items: [me.getMainGrid()]
        }, {
          region: "south",
          height: "60%",
          split: true,
          collapsible: true,
          header: false,
          layout: "border",
          border: 0,
          items: [{
            region: "north",
            bodyStyle: "border-width:1px 1px 0px 1px",
            height: 40,
            layout: {
              type: "table",
              columns: 5
            },
            bodyPadding: 10,
            items: me.getBillSummaryCmp()
          }, {
            region: "center",
            border: 0,
            layout: "fit",
            items: me.getDetailGrid()
          }]
        }]
      }]
    });

    me.callParent(arguments);

    me.editSummaryRef = PCL.getCmp(me.buildId(me, "editSummaryRef"));
    me.editSummarySupplier = PCL.getCmp(me.buildId(me, "editSummarySupplier"));
    me.editSummaryWarehouse = PCL.getCmp(me.buildId(me, "editSummaryWarehouse"));

    me.pagingToobar = PCL.getCmp(me.buildId(me, "pagingToobar"));

    me.buttonEdit = PCL.getCmp(me.buildId(me, "buttonEdit"));
    me.buttonDelete = PCL.getCmp(me.buildId(me, "buttonDelete"));
    me.buttonCommit = PCL.getCmp(me.buildId(me, "buttonCommit"));

    me.editQueryBillStatus = PCL.getCmp(me.buildId(me, "editQueryBillStatus"));
    me.editQueryRef = PCL.getCmp(me.buildId(me, "editQueryRef"));
    me.editQueryFromDT = PCL.getCmp(me.buildId(me, "editQueryFromDT"));

    me.editQueryToDT = PCL.getCmp(me.buildId(me, "editQueryToDT"));
    me.editQuerySupplier = PCL.getCmp(me.buildId(me, "editQuerySupplier"));
    me.editQueryWarehouse = PCL.getCmp(me.buildId(me, "editQueryWarehouse"));
    me.editQueryPaymentType = PCL.getCmp(me.buildId(me, "editQueryPaymentType"));
    me.editQueryGoods = PCL.getCmp(me.buildId(me, "editQueryGoods"));

    // AFX: 查询控件input List
    me.__editorList = [
      me.editQueryBillStatus,
      me.editQueryRef,
      me.editQueryFromDT,
      me.editQueryToDT,
      me.editQuerySupplier,
      me.editQueryWarehouse,
      me.editQueryPaymentType,
      me.editQueryGoods];

    me._keyMapMain = PCL.create("PCL.util.KeyMap", PCL.getBody(), [{
      key: "N",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        // 判断权限
        if (me.getPermission().add != "1") {
          return;
        }

        me._onAddBill.apply(me, []);
      },
      scope: me
    }, {
      key: "Q",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }
        PCL.getCmp(me.buildId(me, "editQueryRef")).focus();
      },
      scope: me
    }, {
      key: "H",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        const panel = PCL.getCmp(me.buildId(me, "panelQueryCmp"));
        if (panel.getCollapsed()) {
          panel.expand();
        } else {
          panel.collapse();
        };
      },
      scope: me
    },
    ]);

    me.refreshMainGrid();
  },

  /**
   * @private
   */
  getToolbarCmp() {
    const me = this;

    let result = [];
    let list = [];

    // 新建
    if (me.getPermission().add == "1") {
      result.push({
        iconCls: "PSI-tb-new",
        text: "新建采购入库单 <span class='PSI-shortcut-DS'>Alt + N</span>",
        tooltip: "快捷键：Alt + N",
        ...PSI.Const.BTN_STYLE,
        id: "buttonAdd",
        scope: me,
        handler: me._onAddBill
      });
    }

    // 变更
    list = [];
    if (me.getPermission().edit == "1") {
      list.push({
        text: "编辑采购入库单",
        scope: me,
        handler: me._onEditBill,
        id: me.buildId(me, "buttonEdit")
      });
    }
    if (me.getPermission().del == "1") {
      list.push({
        text: "删除采购入库单",
        scope: me,
        handler: me._onDeleteBill,
        id: me.buildId(me, "buttonDelete")
      });
    }
    if (list.length > 0) {
      if (result.length > 0) {
        result.push("-");
      }

      result.push({
        text: "变更",
        ...PSI.Const.BTN_STYLE,
        menu: list
      });
    }

    // 提交
    if (me.getPermission().commit == "1") {
      if (result.length > 0) {
        result.push("-");
      }

      result.push({
        iconCls: "PSI-tb-commit",
        text: "提交入库",
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler: me._onCommit,
        id: me.buildId(me, "buttonCommit")
      });
    }

    // 导出
    list = [];
    if (me.getPermission().genPDF == "1") {
      list.push({
        text: "单据生成pdf",
        id: "buttonPDF",
        iconCls: "PSI-button-pdf",
        scope: me,
        handler: me._onPDF
      });
    }
    if (list.length > 0) {
      if (result.length > 0) {
        result.push("-");
      }

      result.push({
        text: "导出",
        ...PSI.Const.BTN_STYLE,
        menu: list
      });
    }

    // 打印
    list = [];
    if (me.getPermission().print == "1") {
      if (result.length > 0) {
        result.push("-");
      }

      list.push({
        text: "打印预览",
        iconCls: "PSI-button-print-preview",
        scope: me,
        handler: me._onPrintPreview
      }, {
        text: "直接打印",
        iconCls: "PSI-button-print",
        scope: me,
        handler: me._onPrint
      });

      result.push({
        text: "打印",
        ...PSI.Const.BTN_STYLE,
        menu: list
      });
    }

    // 指南
    // 关闭
    if (result.length > 0) {
      result.push("-");
    }
    result.push({
      iconCls: "PSI-tb-help",
      text: "指南",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        window.open(me.URL("Home/Help/index?t=pwbill"));
      }
    }, "-", {
      iconCls: "PSI-tb-close",
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        me.closeWindow();
      }
    });

    result = result.concat(me.getPagination()).concat(me.getShortcutCmp());

    return result;
  },

  /**
   * @private
   */
  getQueryCmp() {
    const me = this;
    return [{
      xtype: "container",
      height: 26,
      html: `<h2 style='margin-left:20px;margin-top:18px;color:#595959;display:inline-block'>采购入库</h2>
            &nbsp;&nbsp;<span style='color:#8c8c8c'>单据列表</span>
            <div style='float:right;display:inline-block;margin:10px 0px 0px 20px;border-left:1px solid #e5e6e8;height:40px'>&nbsp;</div>`
    }, {
      id: me.buildId(me, "editQueryBillStatus"),
      xtype: "combo",
      queryMode: "local",
      editable: false,
      valueField: "id",
      labelWidth: 40,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "状态",
      margin: "5, 0, 0, 0",
      store: PCL.create("PCL.data.ArrayStore", {
        fields: ["id", "text"],
        data: [[-1, "全部"], [0, "待入库"], [1000, "已入库"],
        [2000, "部分退货"], [3000, "全部退货"]]
      }),
      value: -1,
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryRef"),
      labelAlign: "right",
      labelSeparator: "",
      labelWidth: 90,
      width: 220,
      fieldLabel: "单号 <span class='PSI-shortcut-DS'>Alt + Q</span>",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryFromDT"),
      xtype: "datefield",
      margin: "5, 0, 0, 0",
      format: "Y-m-d",
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "业务日期（起）",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryToDT"),
      xtype: "datefield",
      margin: "5, 0, 0, 0",
      format: "Y-m-d",
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "业务日期（止）",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQuerySupplier"),
      xtype: "psi_supplierfield",
      parentCmp: me,
      showModal: true,
      labelAlign: "right",
      labelSeparator: "",
      labelWidth: 60,
      margin: "5, 0, 0, 0",
      fieldLabel: "供应商",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      xtype: "container",
    }, {
      id: me.buildId(me, "editQueryWarehouse"),
      xtype: "psi_warehousefield",
      parentCmp: me,
      showModal: true,
      labelAlign: "right",
      labelSeparator: "",
      labelWidth: 40,
      margin: "5, 0, 0, 0",
      fieldLabel: "仓库",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryPaymentType"),
      labelAlign: "right",
      labelSeparator: "",
      labelWidth: 70,
      fieldLabel: "付款方式",
      margin: "5, 0, 0, 0",
      xtype: "combo",
      queryMode: "local",
      editable: false,
      valueField: "id",
      store: PCL.create("PCL.data.ArrayStore", {
        fields: ["id", "text"],
        data: [[-1, "全部"], [0, "记应付账款"], [1, "现金付款"],
        [2, "用预付款支付"]]
      }),
      value: -1,
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryGoods"),
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "物料",
      margin: "5, 0, 0, 0",
      xtype: "psi_goodsfield",
      showModal: true,
      listeners: {
        specialkey: {
          fn: me.__onLastEditSpecialKey,
          scope: me
        }
      }
    }, {
      xtype: "container",
      colspan: 2,
      items: [{
        xtype: "button",
        text: "查询",
        cls: "PSI-Query-btn1",
        width: 100,
        height: 26,
        margin: "5 0 0 10",
        handler: me._onQuery,
        scope: me
      }, {
        xtype: "button",
        text: "清空查询条件",
        cls: "PSI-Query-btn2",
        width: 100,
        height: 26,
        margin: "5, 0, 0, 10",
        handler: me._onClearQuery,
        scope: me
      }, {
        xtype: "button",
        text: "隐藏工具栏 <span class='PSI-shortcut-DS'>Alt + H</span>",
        cls: "PSI-Query-btn3",
        width: 140,
        height: 26,
        iconCls: "PSI-button-hide",
        margin: "5 0 0 20",
        handler() {
          PCL.getCmp(me.buildId(me, "panelQueryCmp")).collapse();
        },
        scope: me
      }]
    }];
  },

  /**
   * @private
   */
  getBillSummaryCmp() {
    const me = this;

    const fieldProps = {
      xtype: "textfield",
      readOnly: true,
      labelSeparator: "",
      labelAlign: "right",
    };
    return [{
      xtype: "container",
      height: 22,
      html: "<span style='padding:0px;margin:0px 0px 0px -5px;border-left: 5px solid #9254de'></span>",
    }, {
      id: me.buildId(me, "editSummaryRef"),
      fieldLabel: "入库单号",
      labelWidth: 60,
      value: "",
      ...fieldProps,
    }, {
      id: me.buildId(me, "editSummarySupplier"),
      fieldLabel: "供应商",
      labelWidth: 70,
      value: "",
      colspan: 2,
      width: 430,
      ...fieldProps,
    }, {
      id: me.buildId(me, "editSummaryWarehouse"),
      fieldLabel: "入库仓库",
      labelWidth: 70,
      value: "",
      ...fieldProps,
    }];
  },

  /**
   * @private
   */
  getMainGrid() {
    const me = this;
    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "PWBill");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "ref", "bizDate", "supplierName",
        "warehouseName", "inputUserName", "bizUserName",
        "billStatus", "billStatusCode", "amount", "dateCreated",
        "paymentType", "billMemo", "expandByBOM",
        "wspBillRef", "tax", "moneyWithTax"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 20,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0001/Purchase/pwbillList"),
        reader: {
          root: 'dataList',
          totalProperty: 'totalCount'
        }
      }
    });
    store.on("beforeload", () => {
      store.proxy.extraParams = me.getQueryParam();
    });
    store.on("load", (e, records, successful) => {
      if (successful) {
        me.gotoMainGridRecord(me._lastId);
      }
    });

    me._mainGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      viewConfig: {
        enableTextSelection: true
      },
      border: 1,
      columnLines: true,
      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [{
          xtype: "rownumberer",
          text: "#",
          width: 50
        }, {
          header: "状态",
          dataIndex: "billStatus",
          width: 80,
          renderer(value) {
            if (value == "待入库") {
              return "<span style='color:red'>" + value
                + "</span>";
            } else if (value == "部分退货") {
              return "<span style='color:blue'>" + value
                + "</span>";
            } else if (value == "全部退货") {
              return "<span style='color:green'>" + value
                + "</span>";
            } else {
              return value;
            }
          }
        }, {
          header: "入库单号",
          dataIndex: "ref",
          width: 120
        }, {
          header: "业务日期",
          dataIndex: "bizDate",
          width: 90,
          align: "center"
        }, {
          header: "供应商",
          dataIndex: "supplierName",
          width: 300
        }, {
          header: "采购金额",
          dataIndex: "amount",
          align: "right",
          xtype: "numbercolumn",
          width: 90,
          hidden: me.getPermission().viewPrice == "0"
        }, {
          header: "税金",
          dataIndex: "tax",
          align: "right",
          xtype: "numbercolumn",
          width: 90,
          hidden: me.getPermission().viewPrice == "0"
        }, {
          header: "价税合计",
          dataIndex: "moneyWithTax",
          align: "right",
          xtype: "numbercolumn",
          width: 90,
          hidden: me.getPermission().viewPrice == "0"
        }, {
          header: "付款方式",
          dataIndex: "paymentType",
          width: 100,
          renderer(value) {
            if (value == 0) {
              return "记应付账款";
            } else if (value == 1) {
              return "现金付款";
            } else if (value == 2) {
              return "用预付款支付";
            } else {
              return "";
            }
          }
        }, {
          header: "入库仓库",
          dataIndex: "warehouseName"
        }, {
          header: "业务员",
          dataIndex: "bizUserName"
        }, {
          header: "制单人",
          dataIndex: "inputUserName"
        }, {
          header: "制单时间",
          dataIndex: "dateCreated",
          width: 150
        }, {
          header: "备注",
          dataIndex: "billMemo",
          width: 150
        }, {
          header: "自动拆分?",
          dataIndex: "expandByBOM",
          width: 80,
          align: "center",
          renderer(value) {
            if (parseInt(value) == 1) {
              return "▲";
            } else {
              return "";
            }
          }
        }, {
          header: "拆分单号",
          dataIndex: "wspBillRef",
          width: 140,
          renderer(value) {
            if (value) {
              return "<a href='"
                + PSI.Const.BASE_URL
                + "SLN0001/Bill/viewIndex?fid=2001&refType="
                + encodeURIComponent("存货拆分")
                + "&ref="
                + encodeURIComponent(value)
                + "' target='_blank'>" + value
                + "</a>";
            } else {
              return "";
            }
          }
        }]
      },
      store: store,
      listeners: {
        select: {
          fn: me._onMainGridSelect,
          scope: me
        },
        itemdblclick: {
          fn: me._onEditBill,
          scope: me
        }
      }
    });

    return me._mainGrid;
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["|", " ",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
   * 分页
   */
  getPagination() {
    const me = this;
    const store = me.getMainGrid().getStore();
    const result = ["->", {
      cls: "PSI-Pagination",
      id: me.buildId(me, "pagingToobar"),
      xtype: "pagingtoolbar",
      border: 0,
      store
    }, "-", {
        xtype: "displayfield",
        value: "每页显示"
      }, {
        id: "comboCountPerPage",
        cls: "PSI-Pagination",
        xtype: "combobox",
        editable: false,
        width: 60,
        store: PCL.create("PCL.data.ArrayStore", {
          fields: ["text"],
          data: [["20"], ["50"], ["100"], ["300"],
          ["1000"]]
        }),
        value: 20,
        listeners: {
          change: {
            fn() {
              store.pageSize = PCL.getCmp("comboCountPerPage").getValue();
              store.currentPage = 1;
              me.pagingToobar.doRefresh();
            },
            scope: me
          }
        }
      }, {
        xtype: "displayfield",
        value: "张单据"
      }];

    return result;
  },

  /**
   * @private
   */
  getDetailGrid() {
    const me = this;
    if (me._detailGrid) {
      return me._detailGrid;
    }

    const modelName = me.buildModelName(me, "PWBillDetail");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "goodsCode", "goodsName", "goodsSpec",
        "unitName", "goodsCount", "goodsMoney",
        "goodsPrice", "memo", "taxRate", "tax",
        "moneyWithTax", "goodsPriceWithTax", "rejGoodsCount", "realGoodsCount"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._detailGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      viewConfig: {
        enableTextSelection: true
      },
      columnLines: true,
      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [PCL.create("PCL.grid.RowNumberer", {
          text: "#",
          width: 40
        }), {
          header: "物料编码",
          dataIndex: "goodsCode"
        }, {
          header: "品名/规格型号",
          dataIndex: "goodsName",
          width: 330,
          renderer(value, metaData, record) {
            return record.get("goodsName") + " " + record.get("goodsSpec");
          }
        }, {
          header: "入库数量",
          width: 80,
          dataIndex: "goodsCount",
          align: "right"
        }, {
          header: "退货数量",
          width: 80,
          dataIndex: "rejGoodsCount",
          align: "right"
        }, {
          header: "实际入库数量",
          width: 100,
          dataIndex: "realGoodsCount",
          align: "right"
        }, {
          header: "单位",
          dataIndex: "unitName",
          width: 50,
          align: "center"
        }, {
          header: "采购单价",
          dataIndex: "goodsPrice",
          align: "right",
          xtype: "numbercolumn",
          width: 90,
          hidden: me.getPermission().viewPrice == "0"
        }, {
          header: "采购金额",
          dataIndex: "goodsMoney",
          align: "right",
          xtype: "numbercolumn",
          width: 90,
          hidden: me.getPermission().viewPrice == "0"
        }, {
          header: "税率(%)",
          dataIndex: "taxRate",
          align: "right",
          xtype: "numbercolumn",
          format: "0",
          hidden: me.getPermission().viewPrice == "0",
          width: 60
        }, {
          header: "税金",
          dataIndex: "tax",
          align: "right",
          xtype: "numbercolumn",
          width: 90,
          hidden: me.getPermission().viewPrice == "0"
        }, {
          header: "价税合计",
          dataIndex: "moneyWithTax",
          align: "right",
          xtype: "numbercolumn",
          width: 90,
          hidden: me.getPermission().viewPrice == "0"
        }, {
          header: "含税价",
          dataIndex: "goodsPriceWithTax",
          align: "right",
          xtype: "numbercolumn",
          width: 90,
          hidden: me.getPermission().viewPrice == "0"
        }, {
          header: "备注",
          dataIndex: "memo",
          width: 200
        }]
      },
      store: store
    });

    return me._detailGrid;
  },

  /**
   * @private
   */
  refreshMainGrid(id) {
    const me = this;
    me.resetSummaryInput();

    me.buttonEdit?.setDisabled(true);
    me.buttonDelete?.setDisabled(true);
    me.buttonCommit?.setDisabled(true);

    const gridDetail = me.getDetailGrid();
    gridDetail.getStore().removeAll();

    me.pagingToobar.doRefresh();
    me._lastId = id;
  },

  /**
   * 新增采购入库单
   * 
   * @private
   */
  _onAddBill() {
    const me = this;

    if (me.getPermission().viewPrice == "0") {
      // 没有查看单价权限，这个时候就不能新建采购入库单
      const info = "没有赋权[采购入库-采购单价和金额可见]，所以不能新建采购入库单";
      me.showInfo(info);
      return;
    }

    const form = PCL.create("PSI.SLN0001.Purchase.PWEditForm", {
      parentForm: me,
      showAddGoodsButton: me.getPermission().showAddGoodsButton,
      viewPrice: me.getPermission().viewPrice == "1"
    });
    form.show();
  },

  /**
   * 编辑采购入库单
   * 
   * @private
   */
  _onEditBill() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择要编辑的采购入库单");
      return;
    }
    const bill = item[0];

    const form = PCL.create("PSI.SLN0001.Purchase.PWEditForm", {
      parentForm: me,
      entity: bill,
      showAddGoodsButton: me.getPermission().showAddGoodsButton,
      viewPrice: me.getPermission().viewPrice == "1"
    });
    form.show();
  },

  /**
   * 删除采购入库单
   * 
   * @private
   */
  _onDeleteBill() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要删除的采购入库单");
      return;
    }

    const bill = item[0];

    if (bill.get("billStatus") == "已入库") {
      me.showInfo("当前采购入库单已经提交入库，不能删除");
      return;
    }

    const store = me.getMainGrid().getStore();
    let index = store.findExact("id", bill.get("id"));
    index--;
    let preIndex = null;
    const preItem = store.getAt(index);
    if (preItem) {
      preIndex = preItem.get("id");
    }

    const info = `请确认是否删除采购入库单: <span style='color:red'>${bill.get("ref")}</span> ？`;
    const confirmFunc = () => {
      const el = PCL.getBody();
      el.mask("正在删除中...");

      const r = {
        url: me.URL("SLN0001/Purchase/deletePWBill"),
        params: {
          id: bill.get("id")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.refreshMainGrid(preIndex);
              me.tip("成功完成删除操作", true);
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };
    me.confirm(info, confirmFunc);
  },

  /**
   * @private
   */
  resetSummaryInput() {
    const me = this;
    me.editSummaryRef.setValue("");
    me.editSummarySupplier.setValue("");
    me.editSummaryWarehouse.setValue("");
  },

  /**
   * @private
   */
  _onMainGridSelect() {
    const me = this;

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.buttonEdit?.setDisabled(true);
      me.buttonDelete?.setDisabled(true);
      me.buttonCommit?.setDisabled(true);

      return;
    }

    const bill = item[0];
    const bsc = parseInt(bill.get("billStatusCode"));
    const commited = bsc > 0;

    const buttonEdit = me.buttonEdit;
    buttonEdit?.setDisabled(false);
    if (commited) {
      buttonEdit?.setText("查看采购入库单");
    } else {
      buttonEdit?.setText("编辑采购入库单");
    }

    me.buttonDelete?.setDisabled(commited);
    me.buttonCommit?.setDisabled(commited);

    me.editSummaryRef.setValue(bill.get("ref"));
    me.editSummarySupplier.setValue(bill.get("supplierName"));
    me.editSummaryWarehouse.setValue(bill.get("warehouseName"));

    me.refreshDetailGrid();
  },

  /**
   * @private
   */
  refreshDetailGrid(id) {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }
    const bill = item[0];

    const grid = me.getDetailGrid();
    const el = grid.getEl();
    el?.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/Purchase/pwBillDetailList"),
      params: {
        pwBillId: bill.get("id")
      },
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);

          if (store.getCount() > 0) {
            if (id) {
              const r = store.findExact("id", id);
              if (r != -1) {
                grid.getSelectionModel().select(r);
              }
            }
          }
        }

        el?.unmask();
      }
    });
  },

  /**
   * 提交采购入库单
   * 
   * @private
   */
  _onCommit() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择要提交的采购入库单");
      return;
    }
    const bill = item[0];

    if (bill.get("billStatus") == "已入库") {
      me.showInfo("当前采购入库单已经提交入库，不能再次提交");
      return;
    }

    const detailCount = me.getDetailGrid().getStore().getCount();
    if (detailCount == 0) {
      me.showInfo("当前采购入库单没有录入物料明细，不能提交");
      return;
    }

    const info = `请确认是否提交单号: <span style='color:red'>${bill.get("ref")}</span> 的采购入库单?`;
    const id = bill.get("id");
    const confirmFunc = () => {
      const el = PCL.getBody();
      el.mask("正在提交中...");
      const r = {
        url: me.URL("SLN0001/Purchase/commitPWBill"),
        params: {
          id: id
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.refreshMainGrid(id);

              me.tip("成功完成提交操作", true);
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };
    me.confirm(info, confirmFunc);
  },

  /**
   * @private
   */
  gotoMainGridRecord(id) {
    const me = this;
    const grid = me.getMainGrid();
    grid.getSelectionModel().deselectAll();
    const store = grid.getStore();
    if (id) {
      const r = store.findExact("id", id);
      if (r != -1) {
        grid.getSelectionModel().select(r);
      } else {
        grid.getSelectionModel().select(0);
      }
    } else {
      grid.getSelectionModel().select(0);
    }
  },

  /**
   * @private
   */
  _onQuery() {
    const me = this;

    me.getMainGrid().getStore().currentPage = 1;
    me.refreshMainGrid();
  },

  /**
   * @private
   */
  _onClearQuery() {
    const me = this;

    me.editQueryBillStatus.setValue(-1);
    me.editQueryRef.setValue(null);
    me.editQueryFromDT.setValue(null);
    me.editQueryToDT.setValue(null);
    me.editQuerySupplier.clearIdValue();
    me.editQueryWarehouse.clearIdValue();
    me.editQueryPaymentType.setValue(-1);
    me.editQueryGoods.clearIdValue();

    me._onQuery();
  },

  /**
   * @private
   */
  getQueryParam() {
    const me = this;

    const result = {
      billStatus: me.editQueryBillStatus.getValue()
    };

    const ref = me.editQueryRef.getValue();
    if (ref) {
      result.ref = ref;
    }

    const supplierId = me.editQuerySupplier.getIdValue();
    if (supplierId) {
      result.supplierId = supplierId;
    }

    const warehouseId = me.editQueryWarehouse.getIdValue();
    if (warehouseId) {
      result.warehouseId = warehouseId;
    }

    const fromDT = me.editQueryFromDT.getValue();
    if (fromDT) {
      result.fromDT = PCL.Date.format(fromDT, "Y-m-d");
    }

    const toDT = me.editQueryToDT.getValue();
    if (toDT) {
      result.toDT = PCL.Date.format(toDT, "Y-m-d");
    }

    const paymentType = me.editQueryPaymentType.getValue();
    result.paymentType = paymentType;

    const goodsId = me.editQueryGoods.getIdValue();
    if (goodsId) {
      result.goodsId = goodsId;
    }

    return result;
  },

  /**
   * @private
   */
  _onPDF() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择要生成pdf文件的采购入库单");
      return;
    }
    const bill = item[0];

    const url = me.URL("SLN0001/Purchase/pwBillPdf?ref=" + bill.get("ref"));
    window.open(url);

    me.focus();
  },

  /**
   * @private
   */
  _onPrintPreview() {
    const me = this;

    if (PSI.Const.ENABLE_LODOP != "1") {
      me.showInfo("请先在业务设置模块中启用Lodop打印");
      return;
    }

    const lodop = getLodop();
    if (!lodop) {
      me.showInfo("没有安装Lodop控件，无法打印");
      return;
    }

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择要打印的采购入库单");
      return;
    }
    const bill = item[0];

    const el = PCL.getBody();
    el.mask("数据加载中...");
    const r = {
      url: me.URL("SLN0001/Purchase/genPWBillPrintPage"),
      params: {
        id: bill.get("id")
      },
      callback(options, success, response) {
        el.unmask();

        if (success) {
          const data = response.responseText;
          me.previewPWBill(bill.get("ref"), data);
        }
      }
    };
    me.ajax(r);
  },

  PRINT_PAGE_WIDTH: "200mm",
  PRINT_PAGE_HEIGHT: "95mm",

  /**
   * @private
   */
  previewPWBill(ref, data) {
    const me = this;

    const lodop = getLodop();
    if (!lodop) {
      me.showInfo("Lodop打印控件没有正确安装");
      return;
    }

    lodop.PRINT_INIT("采购入库单" + ref);
    lodop.SET_PRINT_PAGESIZE(1, me.PRINT_PAGE_WIDTH, me.PRINT_PAGE_HEIGHT,
      "");
    lodop.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", data);
    lodop.PREVIEW("_blank");
  },

  /**
   * @private
   */
  _onPrint() {
    const me = this;

    if (PSI.Const.ENABLE_LODOP != "1") {
      me.showInfo("请先在业务设置模块中启用Lodop打印");
      return;
    }

    const lodop = getLodop();
    if (!lodop) {
      me.showInfo("没有安装Lodop控件，无法打印");
      return;
    }

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择要打印的采购入库单");
      return;
    }
    const bill = item[0];

    const el = PCL.getBody();
    el.mask("数据加载中...");
    const r = {
      url: me.URL("SLN0001/Purchase/genPWBillPrintPage"),
      params: {
        id: bill.get("id")
      },
      callback(options, success, response) {
        el.unmask();

        if (success) {
          const data = response.responseText;
          me.printPWBill(bill.get("ref"), data);
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  printPWBill(ref, data) {
    const me = this;

    const lodop = getLodop();
    if (!lodop) {
      me.showInfo("Lodop打印控件没有正确安装");
      return;
    }

    lodop.PRINT_INIT("采购入库单" + ref);
    lodop.SET_PRINT_PAGESIZE(1, me.PRINT_PAGE_WIDTH, me.PRINT_PAGE_HEIGHT,
      "");
    lodop.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", data);
    lodop.PRINT();
  }
});
